/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sale.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.modules.sale.entity.SaleContacts;
import com.jeeplus.modules.sale.entity.SalePartner;
import com.jeeplus.modules.sale.entity.SaleRecord;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.sale.entity.SaleTask;
import com.jeeplus.modules.sale.service.SaleTaskService;

/**
 * 销售任务Controller
 *
 * @author 卢经纬
 * @version 2018-06-30
 */
@Controller
@RequestMapping(value = "${adminPath}/sale/saleTask")
public class SaleTaskController extends BaseController {


    @Autowired
    private SaleTaskService saleTaskService;

    @ModelAttribute
    public SaleTask get(@RequestParam(required = false) String id) {
        SaleTask entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = saleTaskService.get(id);
        }
        if (entity == null) {
            entity = new SaleTask();
        }
        return entity;
    }

    /**
     * 销售任务列表页面
     */
    @RequiresPermissions("sale:saleTask:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/sale/saleTaskList";
    }

    /**
     * 销售任务列表页面
     */
    @RequiresPermissions("sale:saleTask:list")
    @RequestMapping(value = "saleTaskRecordList")
    public String saleTaskRecordList() {
        return "modules/sale/saleTaskRecordList";
    }


    /**
     * 销售任务列表页面
     */
    @RequiresPermissions("sale:saleTask:list")
    @RequestMapping(value = "weChatList")
    public String weChatList() {
        return "modules/sale/weChatSaleTaskList";
    }


    /**
     * 保存销售任务
     */
    @RequiresPermissions(value = {"sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "weChatSave")
    @ResponseBody
    public String weChatSave(@RequestBody SaleTask saleTask, HttpServletResponse response) throws Exception {
        saleTask.setState(1);
        saleTaskService.save(saleTask);//保存
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        j.setMsg("保存销售任务成功！");
        return renderString(response, j);
    }

    /**
     * 查看，增加，编辑销售任务表单页面
     */
    @RequiresPermissions(value = {"sale:saleTask:view", "sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "saleTaskRecordForm")
    public String saleTaskRecordForm(SaleRecord saleRecord, Model model) {
        model.addAttribute("saleRecord", saleRecord);
        if (StringUtils.isBlank(saleRecord.getId())) {//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/sale/saleTaskRecordForm";
    }


    /**
     * 保存销售任务
     */
    @RequiresPermissions(value = {"sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "saveRecord")
    @ResponseBody
    public String saveRecord(@RequestBody SaleTask saleTask, HttpServletResponse response) throws Exception {
        saleTaskService.saveRecord(saleTask);//保存
        AjaxJson j = new AjaxJson();
        j.setSuccess(true);
        j.setMsg("保存记录成功！");
        return renderString(response, j);
    }

    /**
     * 销售任务列表数据
     */
    @ResponseBody
    @RequiresPermissions("sale:saleTask:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(SaleTask saleTask, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<SaleTask> page = saleTaskService.findPage(new Page<SaleTask>(request, response), saleTask);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑销售任务表单页面
     */
    @RequiresPermissions(value = {"sale:saleTask:view", "sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "weChatForm")
    @ResponseBody
    public String weChatForm(SaleTask saleTask, Model model, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        j.put("saleTask", saleTask);
        j.setSuccess(true);
        j.setMsg("获取成功！");
        return renderString(response, j);
    }

    /**
     * 查看，增加，编辑销售任务表单页面
     */
    @RequiresPermissions(value = {"sale:saleTask:view", "sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(SaleTask saleTask, Model model) {
        model.addAttribute("saleTask", saleTask);
        if (StringUtils.isBlank(saleTask.getId())) {//如果ID是空为添加
            model.addAttribute("isAdd", true);
        }
        return "modules/sale/saleTaskForm";
    }

    /**
     * 保存销售任务
     */
    @RequiresPermissions(value = {"sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public String save(SaleTask saleTask, Model model, RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, saleTask)) {
            return form(saleTask, model);
        }
        //新增或编辑表单保存
        saleTaskService.save(saleTask);//保存
        addMessage(redirectAttributes, "保存销售任务成功");
        return "redirect:" + Global.getAdminPath() + "/sale/saleTask/?repage";
    }

    /**
     * 保存销售任务
     */
    @RequiresPermissions(value = {"sale:saleTask:add", "sale:saleTask:edit"}, logical = Logical.OR)
    @RequestMapping(value = "finish")
    @ResponseBody
    public String finish(SaleTask saleTask, Model model, RedirectAttributes redirectAttributes, HttpServletResponse response) throws Exception {
        AjaxJson j = new AjaxJson();
        saleTask.setState(2);
        if (!beanValidator(model, saleTask)) {
            return form(saleTask, model);
        }
        //新增或编辑表单保存
        saleTaskService.save(saleTask);//保存
        j.setSuccess(true);
        j.setMsg("关闭成功！");
        return renderString(response, j);
    }

    /**
     * 删除销售任务
     */
    @ResponseBody
    @RequiresPermissions("sale:saleTask:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(SaleTask saleTask, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        saleTaskService.delete(saleTask);
        j.setMsg("删除销售任务成功");
        return j;
    }

    /**
     * 批量删除销售任务
     */
    @ResponseBody
    @RequiresPermissions("sale:saleTask:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            saleTaskService.delete(saleTaskService.get(id));
        }
        j.setMsg("删除销售任务成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("sale:saleTask:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public AjaxJson exportFile(SaleTask saleTask, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "销售任务" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<SaleTask> page = saleTaskService.findPage(new Page<SaleTask>(request, response, -1), saleTask);
            new ExportExcel("销售任务", SaleTask.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出销售任务记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    @ResponseBody
    @RequestMapping(value = "detail")
    public SaleTask detail(String id) {
        return saleTaskService.get(id);
    }


    /**
     * 导入Excel数据
     */
    @RequiresPermissions("sale:saleTask:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<SaleTask> list = ei.getDataList(SaleTask.class);
            for (SaleTask saleTask : list) {
                try {
                    saleTaskService.save(saleTask);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条销售任务记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条销售任务记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入销售任务失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/sale/saleTask/?repage";
    }

    /**
     * 下载导入销售任务数据模板
     */
    @RequiresPermissions("sale:saleTask:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "销售任务数据导入模板.xlsx";
            List<SaleTask> list = Lists.newArrayList();
            new ExportExcel("销售任务数据", SaleTask.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/sale/saleTask/?repage";
    }


}